//
//  EditProfileViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/4/21.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "EditProfileViewController.h"
#import "AddressPickerView.h"
#import "AppDelegate.h"
@interface EditProfileViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,AddressPickerViewDelegate>
@property (nonatomic ,strong) AddressPickerView * pickerView;
@property (nonatomic, strong) UIImageView * iconImg;
@property (nonatomic, strong) UIImage     * headImg;
@property (nonatomic, strong) UITextField * userName;
@property (nonatomic, strong) UITextField * UserPhone;
@property (nonatomic ,strong) UIButton    * addressBtn;
@property (nonatomic ,strong) UITextField * textField;
@property (nonatomic ,strong) UITextField * codeField;
@property (nonatomic ,assign) NSInteger     gender;
@property (nonatomic ,strong) NSString    * icoString;

@end

@implementation EditProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=MyString(@"编辑资料");
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MainW, MainH-64) style:1];
    tableView.backgroundColor=Gray_Color;
    tableView.delegate = self;
    tableView.separatorColor=SeparatorColor;
    tableView.separatorInset=UIEdgeInsetsZero;
    tableView.separatorStyle=0;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    [self.view addSubview:self.pickerView];
	
	UIButton *rightB = [UIButton buttonWithType:UIButtonTypeCustom];
	[rightB setTitle:MyString(@"保存") forState:UIControlStateNormal];
	[rightB addTarget:self action:@selector(SaveBtnClick) forControlEvents:UIControlEventTouchUpInside];
	[rightB setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	rightB.titleLabel.font = [UIFont systemFontOfSize:14];
	
//    UIBarButtonItem*item=[[UIBarButtonItem alloc]initWithTitle:MyString(@"保存") style:UIBarButtonItemStyleDone target:self action:@selector(SaveBtnClick)];
//    [item setTitleTextAttributes:@{NSFontAttributeName:FontAndStyle14,NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
	UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightB];
	
    self.navigationItem.rightBarButtonItem=item;
}
- (AddressPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[AddressPickerView alloc]initWithFrame:CGRectMake(0, MainH-64  , MainW, 215)];
        _pickerView.delegate = self;
    }
    return _pickerView;
}

-(void)SaveBtnClick{
    [self showDialog];
//	[self showLoad];
	
    NSString*urlString=[NSString stringWithFormat:@"%@%@",baseURL,API_EDITDMINE];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         
                                                         @"text/html",
                                                         
                                                         @"image/jpeg",
                                                         
                                                         @"image/png",
                                                         
                                                         @"application/octet-stream",
                                                         
                                                         @"text/json",
                                                         
                                                         nil];
    
//    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
//    
//    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        UIImage *image = self.iconImg.image;
        
//        NSData *data = UIImagePNGRepresentation(image);
	NSData *data = UIImageJPEGRepresentation(image, 0.2);

        //上传的参数(上传图片，以文件流的格式)
        
        [formData appendPartWithFileData:data
         
                                    name:@"avatar"
         
                                fileName:@"gauge.png"
         
                                mimeType:@"image/png"];
        [formData appendPartWithFormData:[[NSString stringWithFormat:@"%@",[ZJUserDefaultsTools getCurrentUserID]] dataUsingEncoding:NSUTF8StringEncoding] name:@"userId"];
        [formData appendPartWithFormData:[self.userName.text dataUsingEncoding:NSUTF8StringEncoding] name:@"nickname"];
        [formData appendPartWithFormData:[[NSString stringWithFormat:@"%ld",(long)self.gender] dataUsingEncoding:NSUTF8StringEncoding] name:@"gender"];
        [formData appendPartWithFormData:[self.textField.text dataUsingEncoding:NSUTF8StringEncoding] name:@"district"];
        [formData appendPartWithFormData:[self.UserPhone.text dataUsingEncoding:NSUTF8StringEncoding] name:@"contactPhone"];
        [formData appendPartWithFormData:[self.codeField.text dataUsingEncoding:NSUTF8StringEncoding] name:@"inviterCode"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //NSLog(@"保存成功:%@",responseObject);
        [self dismissDialog];
//		[self hidLoad];
		
        [MBProgressHUD showSuccess:MyString(@"保存成功!")];
        [ZJUserDefaultsTools saveUserInfoLocal:responseObject];
//        [[NSUserDefaults standardUserDefaults] setObject:self.userName.text forKey:NICK_NAME];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self dismissDialog];
//		[self hidLoad];
        [MBProgressHUD showError:MyString(@"保存失败!")];
    }];
    
    
   
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 6;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 49;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"celll"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"celll"];
    }
    cell.selectionStyle=0;
    cell.accessoryType=1;
    cell.textLabel.textColor=TextColor3;
    cell.textLabel.font=FontAndStyle14;
    cell.detailTextLabel.textColor=TextColor6;
    cell.detailTextLabel.font=FontAndStyle14;
    if (indexPath.section==0) {
        cell.textLabel.text=MyString(@"头像");
        UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeIconImg)];
        UIImageView * iconImg = [[UIImageView alloc] initWithFrame:CGRectMake(MainW-70, 5, 40, 40)];
       [iconImg sd_setImageWithURL:[NSURL URLWithString:self.mineDic[@"avatar"]] placeholderImage:[UIImage imageNamed:@"star"]];;
        [cell addSubview:iconImg];
        self.iconImg=iconImg;
        iconImg.userInteractionEnabled = YES;
         [iconImg addGestureRecognizer:gesture];
        ViewRadius(iconImg, 20);
    }else if (indexPath.section==1){
        cell.textLabel.text=MyString(@"性别");
        if ([self.mineDic[@"gender"] intValue]==1) {
            cell.detailTextLabel.text=MyString(@"男");
            self.gender=1;
        }else{
            cell.detailTextLabel.text=MyString(@"女");
            self.gender=2;
            
        }
    }else if (indexPath.section==2){
        cell.accessoryType=0;
        cell.textLabel.text=MyString(@"昵称");
        UITextField * TF_name = [[UITextField alloc] initWithFrame:CGRectMake(100, 5, MainW-100-20, 40)];
        self.userName = TF_name;
        //        TF_name.font = [UIFont systemFontOfSize:16];
        TF_name.textColor = TextColor6;
        TF_name.delegate = self;
        TF_name.tag=11;
        TF_name.font=FontAndStyle14;
        TF_name.textAlignment = NSTextAlignmentRight;
        [cell addSubview:TF_name];
        TF_name.text = self.mineDic[@"nickname"];
    }else if (indexPath.section==3){
        cell.accessoryType=0;
        cell.textLabel.text=MyString(@"联系电话");
        UITextField * TF_name = [[UITextField alloc] initWithFrame:CGRectMake(100, 5, MainW-100-20, 40)];
        self.UserPhone = TF_name;
        //        TF_name.font = [UIFont systemFontOfSize:16];
        TF_name.textColor = TextColor6;
        TF_name.delegate = self;
        TF_name.tag=10;
        TF_name.font=FontAndStyle14;
        TF_name.textAlignment = NSTextAlignmentRight;
        [cell addSubview:TF_name];
        TF_name.text =[NSString stringWithFormat:@"%@",self.mineDic[@"contactPhone"]];
    }else if (indexPath.section==4){
        cell.textLabel.text=MyString(@"地区");
        UITextField * TF_name = [[UITextField alloc] initWithFrame:CGRectMake(100, 5, MainW-100-30, 40)];
        TF_name.textColor = TextColor6;
        TF_name.delegate = self;
        TF_name.tag=10;
        TF_name.font=FontAndStyle14;
        TF_name.textAlignment = NSTextAlignmentRight;
        [cell addSubview:TF_name];
        TF_name.text = self.mineDic[@"district"];
        UIButton *csClick=[[UIButton alloc]initWithFrame:CGRectMake(100, 0, MainW-100, 49)];
        self.addressBtn=csClick;
        [csClick addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:csClick];
        self.textField=TF_name;
        
    }else if (indexPath.section==5){
        cell.accessoryType=0;
        cell.textLabel.text=MyString(@"邀请码");
        UITextField * TF_name = [[UITextField alloc] initWithFrame:CGRectMake(100, 5, MainW-100-20, 40)];
        TF_name.textColor = TextColor6;
        TF_name.delegate = self;
        TF_name.tag=10;
        TF_name.font=FontAndStyle14;
        TF_name.textAlignment = NSTextAlignmentRight;
        [cell addSubview:TF_name];
        NSString *code=[NSString stringWithFormat:@"%@",self.mineDic[@"inviterCode"]];
        if (code.length==0) {
            TF_name.placeholder=@"请输入要绑定的邀请码";
            TF_name.enabled=YES;
        }else{
            TF_name.text = self.mineDic[@"inviterCode"];
            TF_name.enabled=NO;
            
        }
        
        self.codeField=TF_name;
        
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (indexPath.section ==1) {
        [self.pickerView hide];
        self.addressBtn.selected=NO;
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
            
        }];
        UIAlertAction *camera = [UIAlertAction actionWithTitle:MyString(@"男") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            cell.detailTextLabel.text =MyString(@"男");
            self.gender=1;
            //[self changeSex:@"男"];
        }];
        UIAlertAction *picture = [UIAlertAction actionWithTitle:MyString(@"女") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            cell.detailTextLabel.text = MyString(@"女");
            self.gender=2;
            //[self changeSex:@"女"];
            
        }];
        UIAlertAction *baomin = [UIAlertAction actionWithTitle:MyString(@"保密") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            cell.detailTextLabel.text = MyString(@"保密");
            self.gender=0;
            //[self changeSex:@"女"];
            
        }];
        [alertVc addAction:cancle];
        [alertVc addAction:camera];
        [alertVc addAction:picture];
        [alertVc addAction:baomin];
        [self presentViewController:alertVc animated:YES completion:nil];
    }

}
- (void)btnClick:(UIButton *)btn{
    [self.view endEditing:YES];
    btn.selected = !btn.selected;
    if (btn.selected) {
        [self.pickerView show];
    }else{
        [self.pickerView hide];
    }
}
#pragma mark - AddressPickerViewDelegate
- (void)cancelBtnClick{
    //NSLog(@"点击了取消按钮");
    [self btnClick:_addressBtn];
}
- (void)sureBtnClickReturnProvince:(NSString *)province City:(NSString *)city Area:(NSString *)area{
    self.textField.text=[NSString stringWithFormat:@"%@%@%@",province,city,area];
    [self btnClick:_addressBtn];
}

#pragma mark -------- 会员名修改
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [self.pickerView hide];
    self.addressBtn.selected=NO;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    switch (textField.tag) {
        case 10:
        {
            //NSLog(@"号码");
        }
            break;
        case 11:
        {
            if (IsStrEmpty(textField.text)) {
                [MBProgressHUD showError:MyString(@"会员名不能为空")];
                return;
            }
        }
            break;
            
        default:
            break;
    }
}
#pragma mark ------ 换头像
- (void)changeIconImg
{
    [self.pickerView hide];
    self.addressBtn.selected=NO;
    UIAlertController* alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    /*UIAlertControllerStyleActionSheet  警告框的样式:底部*/
    [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto]; /*拍照*/
    }]];
    [alertC addAction:[UIAlertAction actionWithTitle:@"我的相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LocalPhoto]; /*从相册*/
    }]];
    
    [self presentViewController:alertC animated:YES completion:nil];
}
/**
 * 从相册选择
 */
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

/**
 * 拍照
 */
-(void)takePhoto
{
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        [MBProgressHUD showError:@"该设备无摄像头"]; //跳出提示
    }
}
/**
 * 图像选取器的委托方法，选完图片后回调该方法
 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    
        //关闭相册界面
    if (image!= nil)
    {
        self.iconImg.image=image;
        [picker dismissViewControllerAnimated:YES completion:nil];
    }

    
    
}
// 相机选择取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)changeFaceImg:(NSString *)userimg small:(NSString *)userlittleimg userid:(NSString *)userid
{
    
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //    UIWindow * window1 = (UIWindow *)self.view.superview;
    //    //NSLog(@"%@",window1);
    AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow * window2 = app.window;
    //NSLog(@"%@",window2);
    UITouch * touch = touches.anyObject;
    CGPoint location2 = [touch locationInView:window2];
    NSLog(@"%@",NSStringFromCGPoint(location2));
}
@end
